package j.framework.tags.form;

import j.framework.tags.TagUtils;
import j.util.StringUtils;
import j.wcs.cache.dict.DictItem;
import j.wcs.core.WcsContext;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.util.List;

/**
 * 单选按钮组
 * User: jason
 * Date: 2015/4/3 16:04
 */
public class RadioGroupTag extends TagSupport {
    private String name;
    private List<DictItem> items;//可自行指定选项
    private String dictionaryId;//字典表，单选按钮组项将从此字典表中加载，items及这个参数，必须指定其中一个
    private String onchange; //选项改变时将触发
    private String selectedValue;

    protected Object getFormDataValue(){
        FormTag formTag = TagUtils.getParentAsFormTag(this);
        if(null!=formTag){
            return formTag.getFormDataValue(name);
        }
        return null;
    }

    @Override
    public int doStartTag() throws JspException {
        if(StringUtils.isNullOrEmpty(dictionaryId) &&
                items == null){
            throw new RuntimeException("单选按钮组(RadioGroupTag)必须指定dictionaryId或items其中一项，若都指定，则以items为主！");
        }
        List<DictItem> list = this.items;
        if(null == list){
            list = WcsContext.getContext().getDictItems(dictionaryId);
        }
        String selectedValue = this.selectedValue;
        if(StringUtils.isNullOrEmpty(selectedValue)){
            selectedValue = String.valueOf(getFormDataValue());
        }
        String radioValue;
        final StringBuilder buff = new StringBuilder();
        for(DictItem item : list){
            radioValue = item.getCode();
            if(StringUtils.isNotEmpty(item.getValue())){
                radioValue = item.getValue();
            }
            buff.append("<label>");
            buff.append("<input type='radio' name='").append(name).append("' value='").append(radioValue).append("'");
            if(StringUtils.isNotEmpty(onchange)){
                buff.append(" onchange=\"").append(onchange).append("('").append(radioValue).append("')\"");
            }
            if(StringUtils.isNotEmpty(selectedValue) && selectedValue.equals(radioValue)){
                buff.append(" checked='checked'");
            }
            buff.append("/>").append(item.getName()).append("</label>");
        }
        JspWriter writer = this.pageContext.getOut();
        try {
            writer.write(buff.toString());
        } catch (IOException ignored) {}
        return SKIP_BODY;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setItems(List<DictItem> items) {
        this.items = items;
    }

    public void setDictionaryId(String dictionaryId) {
        this.dictionaryId = dictionaryId;
    }

    public void setOnchange(String onchange) {
        this.onchange = onchange;
    }

    public void setSelectedValue(String selectedValue) {
        this.selectedValue = selectedValue;
    }
}
